package cn.cdu.medical.controller;

import cn.cdu.basics.baseVo.Result;
import cn.cdu.basics.utils.ResultUtil;
import cn.cdu.basics.utils.SecurityUtil;
import cn.cdu.medical.entity.MedicalRecord;
import cn.cdu.medical.entity.MedicalRecordRevision;
import cn.cdu.medical.service.MedicalRecordService;
import cn.cdu.medical.service.MedicalRecordRevisionService;
import cn.cdu.medical.service.impl.MedicalRecordServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "电子病历接口")
@RequestMapping("/zwz/medical-records")
@CrossOrigin(origins = "*", maxAge = 3600)
public class MedicalRecordController {

    @Autowired
    private MedicalRecordService medicalRecordService;
    
    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private MedicalRecordRevisionService revisionService;

    @GetMapping("/{id}")
    @ApiOperation(value = "获取病历详情")
    public Result<MedicalRecord> getMedicalRecord(@PathVariable String id) {
        try {
            log.debug("Getting medical record: {}", id);
            MedicalRecord record = medicalRecordService.getMedicalRecordDetail(id);
            return ResultUtil.data(record);
        } catch (Exception e) {
            log.error("获取病历失败", e);
            return ResultUtil.error("获取病历失败，请稍后重试：" + e.getMessage());
        }
    }

    @PostMapping("/generate/{consultationId}")
    @ApiOperation(value = "根据问诊记录生成病历")
    public Result<MedicalRecord> generateInitialMedicalRecord(@PathVariable String consultationId) {
        try {
            log.debug("Generating medical record for consultation: {}", consultationId);
            MedicalRecord record = medicalRecordService.generateInitialMedicalRecord(consultationId);
            return ResultUtil.data(record);
        } catch (Exception e) {
            log.error("生成病历失败", e);
            return ResultUtil.error("生成病历失败，请稍后重试：" + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    @ApiOperation("更新病历")
    public Result<MedicalRecord> update(@PathVariable String id, @RequestBody MedicalRecord medicalRecord) {
        try {
            // 获取原有记录
            MedicalRecord originalRecord = medicalRecordService.getById(id);
            if (originalRecord == null) {
                return ResultUtil.error("病历不存在");
            }

            // 设置更新时间和更新人
            String currentUser = securityUtil.getCurrUser().getNickname();
            medicalRecord.setId(id);
            medicalRecord.setUpdateTime(new Date());
            medicalRecord.setUpdatedBy(currentUser);
            
            // 保留原有的order_id
            if (medicalRecord.getOrderId() == null) {
                medicalRecord.setOrderId(originalRecord.getOrderId());
            }

            // 更新记录
            MedicalRecord updatedRecord = medicalRecordService.update(medicalRecord);

            // 创建修订记录
            MedicalRecordRevision revision = new MedicalRecordRevision();
            revision.setRecordId(id);
            
            // 设置修订内容
            StringBuilder revisionContent = new StringBuilder();
            
            // 检查主诉变更
            if (hasContentChanged(originalRecord.getChiefComplaint(), medicalRecord.getChiefComplaint())) {
                revisionContent.append("主诉变更\n");
                addFieldRevision(revision, "主诉", originalRecord.getChiefComplaint(), medicalRecord.getChiefComplaint());
            }
            
            // 检查现病史变更
            if (hasContentChanged(originalRecord.getPresentIllness(), medicalRecord.getPresentIllness())) {
                revisionContent.append("现病史变更\n");
                addFieldRevision(revision, "现病史", originalRecord.getPresentIllness(), medicalRecord.getPresentIllness());
            }
            
            // 检查查体变更
            if (hasContentChanged(originalRecord.getPhysicalExam(), medicalRecord.getPhysicalExam())) {
                revisionContent.append("查体变更\n");
                addFieldRevision(revision, "查体", originalRecord.getPhysicalExam(), medicalRecord.getPhysicalExam());
            }
            
            // 检查恢复建议变更
            if (hasContentChanged(originalRecord.getAdviceContent(), medicalRecord.getAdviceContent()) ||
                hasContentChanged(originalRecord.getAdviceType(), medicalRecord.getAdviceType()) ||
                hasContentChanged(originalRecord.getAdviceTitle(), medicalRecord.getAdviceTitle())) {
                revisionContent.append("恢复建议变更\n");
                addFieldRevision(revision, "恢复建议", 
                    String.format("类型：%s\n标题：%s\n内容：%s", 
                        originalRecord.getAdviceType(), 
                        originalRecord.getAdviceTitle(), 
                        originalRecord.getAdviceContent()),
                    String.format("类型：%s\n标题：%s\n内容：%s", 
                        medicalRecord.getAdviceType(), 
                        medicalRecord.getAdviceTitle(), 
                        medicalRecord.getAdviceContent()));
            }
            
            // 检查辅助检查变更
            if (hasContentChanged(originalRecord.getAuxiliaryExam(), medicalRecord.getAuxiliaryExam())) {
                revisionContent.append("辅助检查变更\n");
                addFieldRevision(revision, "辅助检查", originalRecord.getAuxiliaryExam(), medicalRecord.getAuxiliaryExam());
            }
            
            // 检查诊疗计划变更
            if (hasContentChanged(originalRecord.getTreatmentPlan(), medicalRecord.getTreatmentPlan())) {
                revisionContent.append("诊疗计划变更\n");
                addFieldRevision(revision, "诊疗计划", originalRecord.getTreatmentPlan(), medicalRecord.getTreatmentPlan());
            }
            
            // 检查诊断变更
            if (hasContentChanged(originalRecord.getDiagnosisName(), medicalRecord.getDiagnosisName())) {
                revisionContent.append("诊断变更\n");
                addFieldRevision(revision, "诊断", originalRecord.getDiagnosisName(), medicalRecord.getDiagnosisName());
            }
            
            // 如果有修改内容，保存修订记录
            if (revisionContent.length() > 0) {
                revision.setRevisionContent(revisionContent.toString());
                revision.setCreateBy(currentUser);
                revision.setCreateTime(new Date());

                // 保存修订记录
                revisionService.saveRevision(revision);
            }

            return ResultUtil.data(updatedRecord);
        } catch (Exception e) {
            log.error("更新病历失败", e);
            return ResultUtil.error("更新病历失败：" + e.getMessage());
        }
    }

    /**
     * 检查内容是否发生变化
     */
    private boolean hasContentChanged(String oldContent, String newContent) {
        // 处理空值情况
        oldContent = oldContent == null ? "" : oldContent.trim();
        newContent = newContent == null ? "" : newContent.trim();
        return !oldContent.equals(newContent);
    }

    /**
     * 添加字段修订记录
     */
    private void addFieldRevision(MedicalRecordRevision revision, String fieldName, String oldValue, String newValue) {
        revision.setFieldName(fieldName);
        revision.setOldValue(oldValue == null ? "" : oldValue);
        revision.setNewValue(newValue == null ? "" : newValue);
        revision.setOriginalContent(oldValue == null ? "" : oldValue);
        revision.setRevisedContent(newValue == null ? "" : newValue);
    }
    
    @GetMapping("/user/{userId}")
    @ApiOperation(value = "获取用户的病历列表")
    public Result<List<MedicalRecord>> getUserMedicalRecords(@PathVariable String userId) {
        try {
            log.debug("Getting medical records for user: {}", userId);
            List<MedicalRecord> records = medicalRecordService.getUserMedicalRecords(userId);
            return ResultUtil.data(records);
        } catch (Exception e) {
            log.error("获取用户病历列表失败", e);
            return ResultUtil.error("获取用户病历列表失败，请稍后重试：" + e.getMessage());
        }
    }
    
    @GetMapping("/doctor/{doctorId}")
    @ApiOperation(value = "获取医生的病历列表")
    public Result<List<MedicalRecord>> getDoctorMedicalRecords(@PathVariable String doctorId) {
        try {
            log.debug("Getting medical records for doctor: {}", doctorId);
            List<MedicalRecord> records = medicalRecordService.getDoctorMedicalRecords(doctorId);
            return ResultUtil.data(records);
        } catch (Exception e) {
            log.error("获取医生病历列表失败", e);
            return ResultUtil.error("获取医生病历列表失败，请稍后重试：" + e.getMessage());
        }
    }
    
    @GetMapping("/current-user")
    @ApiOperation(value = "获取当前用户的病历列表")
    public Result<List<MedicalRecord>> getCurrentUserMedicalRecords() {
        try {
            String userId = securityUtil.getCurrUser().getId();
            log.debug("Getting medical records for current user: {}", userId);
            List<MedicalRecord> records = medicalRecordService.getUserMedicalRecords(userId);
            return ResultUtil.data(records);
        } catch (Exception e) {
            log.error("获取当前用户病历列表失败", e);
            return ResultUtil.error("获取当前用户病历列表失败，请稍后重试：" + e.getMessage());
        }
    }
    
    @PostMapping
    @ApiOperation("创建病历")
    public Result<MedicalRecord> createMedicalRecord(@RequestBody MedicalRecord record) {
        try {
            log.debug("Creating medical record: {}", record);
            
            // 设置当前医生信息
            try {
                String doctorId = securityUtil.getCurrUser().getId();
                String doctorName = securityUtil.getCurrUser().getNickname();
                record.setDoctorId(doctorId);
                record.setDoctorName(doctorName);
            } catch (Exception e) {
                log.warn("Failed to get current user: {}", e.getMessage());
            }
            
            MedicalRecord created = medicalRecordService.createMedicalRecord(record);
            return ResultUtil.data(created);
        } catch (Exception e) {
            log.error("创建病历失败", e);
            return ResultUtil.error("创建病历失败，请稍后重试：" + e.getMessage());
        }
    }

    @GetMapping("/consultation/{consultationId}")
    @ApiOperation("获取问诊关联的病历")
    public Result<MedicalRecord> getByConsultationId(@PathVariable String consultationId) {
        try {
            log.debug("Getting medical record for consultation: {}", consultationId);
            MedicalRecordServiceImpl service = (MedicalRecordServiceImpl) medicalRecordService;
            MedicalRecord record = service.getOrCreateMedicalRecordByConsultationId(consultationId);
            return ResultUtil.data(record);
        } catch (Exception e) {
            log.error("获取问诊病历失败", e);
            return ResultUtil.error("获取问诊病历失败，请稍后重试：" + e.getMessage());
        }
    }

    @GetMapping("/patient/{patientId}/current")
    @ApiOperation(value = "获取患者当前病历")
    public Result<MedicalRecord> getCurrentMedicalRecord(@PathVariable String patientId) {
        try {
            log.debug("Getting current medical record for patient: {}", patientId);
            MedicalRecord record = medicalRecordService.getCurrentMedicalRecord(patientId);
            return ResultUtil.data(record);
        } catch (Exception e) {
            log.error("获取患者当前病历失败", e);
            return ResultUtil.error("获取患者当前病历失败，请稍后重试：" + e.getMessage());
        }
    }

    @GetMapping("/patient/{patientId}/history")
    @ApiOperation("获取患者历史病历")
    public Result<List<MedicalRecord>> getPatientHistory(@PathVariable String patientId,
                                                       @RequestParam(required = false) String doctorId,
                                                       @RequestParam(required = false) String deptName) {
        try {
            log.debug("Getting history medical records for patient: {}, doctor: {}, department: {}", patientId, doctorId, deptName);
            
            List<MedicalRecord> records = medicalRecordService.getPatientHistoryRecords(patientId, doctorId, deptName);
            return ResultUtil.data(records);
        } catch (Exception e) {
            log.error("获取患者历史病历列表失败", e);
            return ResultUtil.error("获取患者历史病历列表失败，请稍后重试：" + e.getMessage());
        }
    }

    @GetMapping("/department")
    @ApiOperation(value = "获取医生科室的病历列表")
    public Result<List<MedicalRecord>> getDepartmentRecords() {
        try {
            String doctorId = securityUtil.getCurrUser().getId();
            String deptName = securityUtil.getCurrUser().getDepartmentTitle();
            
            log.debug("Getting department records for doctor: {}, department: {}", doctorId, deptName);
            MedicalRecordServiceImpl service = (MedicalRecordServiceImpl) medicalRecordService;
            List<MedicalRecord> records = service.getDepartmentRecords(doctorId, deptName);
            
            return ResultUtil.data(records);
        } catch (Exception e) {
            log.error("获取科室病历列表失败", e);
            return ResultUtil.error("获取科室病历列表失败，请稍后重试：" + e.getMessage());
        }
    }

    @GetMapping("/{recordId}/revisions")
    @ApiOperation(value = "获取病历修订历史")
    public Result<List<MedicalRecordRevision>> getRevisionHistory(@PathVariable String recordId) {
        try {
            log.debug("Getting revision history for medical record: {}", recordId);
            List<MedicalRecordRevision> revisions = revisionService.getRevisionHistory(recordId);
            return ResultUtil.data(revisions);
        } catch (Exception e) {
            log.error("获取病历修订历史失败", e);
            return ResultUtil.error("获取病历修订历史失败：" + e.getMessage());
        }
    }
} 
 